package controller;


import com.alibaba.dubbo.config.annotation.Reference;
import entity.ResponseResult;
import entity.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import service.UserService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 1、dao层的测试
 * 2、前端逻辑完善
 * 3、网页使用vue
 * 
 */

@RestController
@RequestMapping("/user")
public class UserAction {

    @Reference
    private UserService userService;

    /*
        用户注册 or 修改
     */
    @RequestMapping("/register")
    public ResponseResult register(@RequestBody Users user) {
        ResponseResult responseResult = null;
        System.out.println(user.toString());
        System.out.println("来注册");
        try {
            String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            user.setCreatetime(nowTime);
            if (user.getUid() == null){
                userService.register(user);
                responseResult = new ResponseResult(true,200,"用户添加成功",null);
            }else {
                userService.update(user);
                responseResult = new ResponseResult(true,200,"用户修改成功",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseResult = new ResponseResult(false,200,"失败",null);
        }
        return responseResult;
    }

     /*
        查询所用用户
     */
    @RequestMapping("/findAll")
    public ResponseResult findAll(){
        ResponseResult responseResult = null;
        try{
            List<Users> list = userService.findAll();
            responseResult = new ResponseResult(true,200,"用户查询成功",list);
        }catch (Exception e){
            e.printStackTrace();
            responseResult = new ResponseResult(false,200,"用户查询失败",null);
        }
        return responseResult;
    }

     /*
        根据姓名模糊查询用户
     */
    @RequestMapping("/findByName")
    public ResponseResult findByName(String name){
        ResponseResult responseResult = null;
        try {
            List<Users> list = userService.findByName("%" + name + "%");
            responseResult = new ResponseResult(true,200,"用户查询成功",list);
        }catch (Exception e){
            e.printStackTrace();
            responseResult = new ResponseResult(false,200,"用户查询失败",null);
        }
        return responseResult;
    }

     /*
        根据id删除用户
     */
     @RequestMapping("/delete")
    public ResponseResult delete(int id){

        ResponseResult responseResult = null;
        try{
            userService.delete(id);
            responseResult = new ResponseResult(true,200,"用户删除成功",null);
        }catch (Exception e){
            e.printStackTrace();
            responseResult = new ResponseResult(false,200,"用户删除失败",null);
        }


        return responseResult;
    }

}
